<template>
    <div class="t-1">
        <a-button type="primary"  @click="sendWebSocketMsg()">发送websocket消息到服务器</a-button>
        <br>
        发送到服务器的数据:<a-input v-model:value="toServerMsg" placeholder="输入消息内容" />
        收到服务器发来的消息:<a-input v-model:value="msg" placeholder="Basic usage" />    
    </div>

</template>

<script>
import { getCurrentInstance, defineComponent, ref, reactive,toRef,toRefs,onMounted} from 'vue';
import { message } from "ant-design-vue";
import {$http} from '@/utils/axios';
export default defineComponent({
    name:'Test1Hello',
    setup() {
        onMounted(()=>{
            const wsUrl = 'ws://localhost:10015/websocket'
            let ws = new WebSocket(wsUrl)
            testData.webSocketInstance=ws
            ws.onopen = function(event){
                console.log("连接到websocket成功");
            }
            ws.onmessage = function(event){
                testData.msg = event.data
                console.log("收到websocket数据:",event.data)
                // ws.close()
            }
            ws.onclose = function(event){
                console.log("websocket连接关闭")
            }
        })

        function wsClose(){
            if(testData.webSocketInstance){
                testData.webSocketInstance.close()
                testData.webSocketInstance = null
            }
        }

        const {appContext: {config: {globalProperties: global}}} = getCurrentInstance();
        let testData = reactive({
            msg:"",
            toServerMsg:"",
            webSocketInstance:null
        });

        function sendWebSocketMsg(){
            if(testData.webSocketInstance){
                testData.webSocketInstance.send(testData.toServerMsg)
            }else{
                message.error("未连接到服务器")
            }
            
        }
        

        return {
            ...toRefs(testData),
            sendWebSocketMsg
        };
    }
});
</script>

<style>

</style>